/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.controller.common
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	import mx.core.IFlexDisplayObject;
	import mx.core.Singleton;
	import mx.managers.IPopUpManager;
	
	import org.etherframework.controller.ReactiveCommand;
	import org.etherframework.common.command.ICommand;
	import org.etherframework.common.mediators.facade.IMediatorsFacade;
	import org.etherframework.mediator.IMediator;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;

	public class CreatePopUpCommand extends ReactiveCommand
	{
		private var _type:Class;
		private var _model:PopUpModel;
		private var _parent:DisplayObject;
		private var _modal:Boolean;
		private var _manager:IPopUpManager;
		
		public function initialize(type:Class, parent:DisplayObject, 
								   model:PopUpModel, modal:Boolean = true):ICommand
		{
			_type = type;
			_parent = parent;
			_model = model;
			_modal = modal;
			_manager = IPopUpManager(Singleton.getInstance("mx.managers::IPopUpManager"));
			
			markAsInitialized();
			return this;
		}
		
		override public function observable():IObservable
		{
			return Observable.defer(function():IObservable
			{
				var mediator:IMediator;
				// TODO: Shell we do this via ether.dependencies.getInstance(_type)?
				const view:IModelPopUp = new _type() as IModelPopUp;
				
				if (!view)
					throw new Error("Component " + _type + " should implement IModelPopUp.");
				
				view.model = _model;
				_model.popUp = view;
				
				if (ether.mediators.hasMediatorMapping(_type))
					mediator = ether.mediators.createMediator(DisplayObject(view));
				
				_manager.addPopUp(IFlexDisplayObject(view), _parent, _modal);
				_manager.centerPopUp(view);
				
				var completeEvent:IObservable = Observable.fromEvents(_model, 
					[Event.COMPLETE, Event.CANCEL]);
				
				return completeEvent.take(1);
			});
		}
	}
}